/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
<template>
  <m-popover
    ref="popover"
    :ok-text="item ? $t('Edit') : $t('Submit')"
    @ok="_ok"
    @close="close"
  >
    <template slot="content">
      <div
        class="create-user-model"
        style="padding: 20px;"
      >
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          size="mini"
          label-position="left"
          label-width="100px"
        >
          <el-form-item
            label="用户组"
            prop="userGroup"
          >
            <el-select
              v-model="form.userGroup"
              size="small"
              placeholder="请选择"
              style="width: 100%;"
            >
              <el-option
                v-for="item in userGroupList"
                :key="item.id"
                :label="item.userGroup"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="用户名"
            prop="userName"
          >
            <el-input
              type="input"
              v-model="form.userName"
              maxlength="60"
              size="small"
              :placeholder="$t('Please enter user name')"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="密码"
            prop="userPassword"
          >
            <el-input
              type="password"
              v-model="form.userPassword"
              size="small"
              :placeholder="$t('Please enter your password')"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="角色"
            prop="tenantId"
            v-if="isADMIN"
          >
            <el-select
              v-model="form.tenantId"
              style="width: 100%;"
              size="small"
            >
              <el-option
                v-for="city in tenantList"
                :key="city.id"
                :value="city.id"
                :label="city.code"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="邮件"
            prop="email"
          >
            <el-input
              type="input"
              v-model="form.email"
              size="small"
              :placeholder="$t('Please enter email')"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="手机"
            prop="phone"
          >
            <el-input
              type="input"
              v-model="form.phone"
              size="small"
              :placeholder="$t('Please enter phone number')"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="账号有效期"
            prop="datetime"
          >
            <el-date-picker
              v-model="form.datetime"
              type="datetime"
              size="small"
              style="width: 100%;"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            label="账号有效期"
            prop="userState"
            v-if="showState"
          >
            <el-radio-group
              v-model="form.userState"
              size="small"
            >
              <el-radio :label="'1'">{{$t('Enable')}}</el-radio>
              <el-radio :label="'0'">{{$t('Disable')}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
    </template>
  </m-popover>
</template>
<script>
  import _ from 'lodash'
  import i18n from '@/module/i18n'
  import store from '@/conf/home/store'
  import router from '@/conf/home/router'
  import mPopover from '@/module/components/popup/popover'
  import { mapState, mapGetters } from 'vuex'

  export default {
    name: 'create-user',
    data () {
      /* validatepass */
      const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'))
        } else {
          if (this.form.userPassword !== '') {
            let regPassword = /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?![`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]+$)[`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、0-9A-Za-z]{6,22}$/
            // password
            if (!regPassword.test(value)) {
              return callback(new Error(`${i18n.$t('Password consists of at least two combinations of numbers, letters, and characters, and the length is between 6-22')}`))
            }
          }
          callback()
        }
      }
      return {
        store,
        router,
        queueList: [],
        form: {
          userGroup: '',
          userName: '',
          userPassword: '',
          tenantId: '',
          email: '',
          phone: '',
          datetime: '',
          userState: '1',
        },
        queueName: '',
        tenantList: [],
        showState: true,
        rules: {
          userGroup: [
            { required: true, message: '请选择用户组', trigger: ['change', 'submit'] },
          ],
          userName: [
            { required: true, message: '请输入用户名', trigger: ['blur', 'submit'] },
            { min: 3, max: 39, message: '长度在 3 到 39 个字符', trigger: ['blur', 'submit'] },
          ],
          userPassword: [
            { required: true, message: '请输入确定密码', trigger: ['blur', 'submit'] },
            { validator: validatePass, trigger: ['blur', 'submit'] },
          ],
          tenantId: [
            { required: true, message: '请选择角色', trigger: ['change', 'submit'] },
          ],
          email: [
            { required: true, message: '请输入邮件', trigger: ['blur', 'submit'] },
            { pattern: /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, message: '请输入正确的邮箱', trigger: ['blur', 'submit'] }
          ],
          phone: [
            { required: true, message: '请输入手机号码', trigger: ['blur', 'submit'] },
            { pattern: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/, message: '请输入正确的手机号码', trigger: ['blur', 'submit'] }
          ],
        },
        // Source admin user information
        isADMIN: store.state.user.userInfo.userType === 'ADMIN_USER' && router.history.current.name !== 'account'
      }
    },
    props: {
      item: Object,
      fromUserInfo: Boolean,
    },
    methods: {
      _ok () {
        this.$refs.form.validate(isCheck => {
          if (!isCheck) return
          // The name is not verified
          if (this.item && this.item.groupName === this.groupName) {
            this._submit()
            return
          }
          // Verify username
          this.store.dispatch('security/verifyName', {
            type: 'user',
            userName: this.form.userName
          }).then(res => {
            this._submit()
          }).catch(e => {
            this.$message.error(e.msg || '')
          })
        })
      },
      _getQueueList () {
        return new Promise((resolve, reject) => {
          this.store.dispatch('security/getQueueList').then(res => {
            this.queueList = _.map(res, v => {
              return {
                id: v.id,
                code: v.queueName
              }
            })
            this.$nextTick(() => {
              this.queueName = this.queueList[0].id
            })
            resolve()
          })
        })
      },
      _getTenantList () {
        return new Promise((resolve, reject) => {
          this.store.dispatch('permission/getRoleAll').then(res => {
            this.tenantList = _.map(res, v => {
              return {
                id: v.id,
                code: v.roleName
              }
            })
            this.$nextTick(() => {
              if (this.tenantList.length) {
                this.form.tenantId = this.tenantList[0].id
              }
            })
            resolve()
          })
        })
      },
      _submit () {
        this.$refs.popover.spinnerLoading = true

        let queueCode = ''
        // get queue code
        if (this.queueName !== '') {
          queueCode = this.queueList.length > 0 ? _.find(this.queueList, ['id', this.queueName]).code : ''
        }
        let param = {
          userName: this.form.userName,
          userPassword: this.form.userPassword,
          roleId: this.form.tenantId,
          email: this.form.email,
          queue: queueCode,
          phone: this.form.phone,
          state: this.form.userState
        }

        if (this.item) {
          param.id = this.item.id
        }

        this.store.dispatch(`security/${this.item ? 'updateUser' : 'createUser'}`, param).then(res => {
          this.$refs.popover.spinnerLoading = false
          this.$emit('onUpdate')
          this.$message.success(res.msg)
        }).catch(e => {
          this.$message.error(e.msg || '')
          this.$refs.popover.spinnerLoading = false
        })
      },
      close () {
        this.$emit('close')
      }
    },
    watch: {},
    created () {
      // Administrator gets tenant list
      this.showState = true
      if (this.isADMIN) {
        Promise.all([this._getQueueList(), this._getTenantList()]).then(() => {
          if (this.item) {
            this.form.userName = this.item.userName
            this.form.userPassword = ''
            this.form.email = this.item.email
            this.form.phone = this.item.phone
            // this.state = this.item.state
            this.form.userState = this.item.state + '' || '1'
            this.showState = this.item.id !== this.userInfo.id
            if (this.fromUserInfo || this.item.roleId) {
              this.form.tenantId = this.item.roleId
            }
            this.$nextTick(() => {
              let queue = _.find(this.queueList, ['code', this.item.queue])
              if (queue) {
                this.queueName = queue.id || ''
              }
            })
          }
        })
      } else {
        if (this.item) {
          this.form.userName = this.item.userName
          this.form.userPassword = ''
          this.form.email = this.item.email
          this.form.phone = this.item.phone
          this.state = this.item.state
          this.form.userState = this.state + '' || '1'
          this.showState = this.item.id !== this.userInfo.id
          if (this.fromUserInfo || this.item.roleId) {
            this.form.tenantId = this.item.roleId
          }
          if (this.queueList.length > 0) {
            let queue = _.find(this.queueList, ['code', this.item.queue])
            if (queue) {
              this.queueName = queue.id || ''
            }
          } else {
            this.queueName = ''
          }
        }
      }
    },
    mounted () {
    },
    computed: {
      ...mapState('user', ['userInfo']),
      ...mapGetters('user', ['userGroupList'])
    },
    components: { mPopover }
  }
</script>
